package com.foreveredu.propms.web.struts.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.District;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.PageModel;
import com.foreveredu.propms.domain.Role;
import com.foreveredu.propms.domain.SubDistrict;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.OwnerActionForm;

public class OwnerAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	// 跳转到业主列表页面
	@SuppressWarnings("unchecked")
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		OwnerActionForm oaf = (OwnerActionForm) form;

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
					.getUsername());
		} catch (ClassCastException e) {
			// 用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");

		List<SubDistrict> subDistrictList = null;

		if (roles.contains(role_Admin)) {

			if (oaf.getSubDistrict_id() == 0|| "".equals(oaf.getSubDistrict_id())) {

				int offset = 0;
				String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
				if (pageOffset != null && !pageOffset.equals("")) {
					offset = Integer.parseInt(pageOffset);
				}
				if (offset < 0) {
					return mapping.findForward("ownerList");
				}
				PageModel pm = managementService.findOwnerList(offset);

				subDistrictList = managementService.findSubDistricts();
				request.setAttribute("pm", pm);

			} else {

				int offset = 0;
				String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
				if (pageOffset != null && !pageOffset.equals("")) {
					offset = Integer.parseInt(pageOffset);
				}
				if (offset < 0) {
					return mapping.findForward("ownerList");
				}
				PageModel pm = managementService.findOwnerListBySubDistrict(
						offset, oaf.getSubDistrict_id());

				List<Owner> ownerList = new ArrayList<Owner>();
				for (Iterator<House> houseIter = pm.getDatas().iterator(); houseIter
						.hasNext();) {
					House house = houseIter.next();
					Owner owner = house.getOwner();
					ownerList.add(owner);
					pm.setDatas(ownerList);
				}

				subDistrictList = managementService.findSubDistricts();
				SubDistrict subDistrict =managementService.findSubDistrictById(oaf.getSubDistrict_id());
				request.setAttribute("subDistrict", subDistrict);
				request.setAttribute("pm", pm);
			}

		} else if (roles.contains(role_ChargeMan)) {
			if (oaf.getSubDistrict_id() == 0|| "".equals(oaf.getSubDistrict_id())) {

				// 获取当前物业管理员所在的物业服务处
				District dis = user.getDistrict();

				int offset = 0;
				String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
				if (pageOffset != null && !pageOffset.equals("")) {
					offset = Integer.parseInt(pageOffset);
				}
				if (offset < 0) {
					return mapping.findForward("ownerList");
				}
				PageModel pm = managementService.findOwnerListByDistrict(
						offset, dis.getId());

				List<Owner> ownerList = new ArrayList<Owner>();
				for (Iterator<House> houseIter = pm.getDatas().iterator(); houseIter
						.hasNext();) {
					House house = houseIter.next();
					Owner owner = house.getOwner();
					ownerList.add(owner);
					pm.setDatas(ownerList);
				}
				subDistrictList = managementService
						.findSubDistrictsOfDistrict(dis);
				request.setAttribute("pm", pm);
			} else {
				
				District dis = user.getDistrict();
				int offset = 0;
				String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
				if (pageOffset != null && !pageOffset.equals("")) {
					offset = Integer.parseInt(pageOffset);
				}
				if (offset < 0) {
					return mapping.findForward("ownerList");
				}
				PageModel pm = managementService.findOwnerListBySubDistrict(offset, oaf.getSubDistrict_id());

				List<Owner> ownerList = new ArrayList<Owner>();
				for (Iterator<House> houseIter = pm.getDatas().iterator(); houseIter
						.hasNext();) {
					House house = houseIter.next();
					Owner owner = house.getOwner();
					ownerList.add(owner);
					pm.setDatas(ownerList);
				}

				subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
				SubDistrict subDistrict =managementService.findSubDistrictById(oaf.getSubDistrict_id());
				request.setAttribute("subDistrict", subDistrict);
				request.setAttribute("pm", pm);

			}
		}
		request.setAttribute("subDistrictList", subDistrictList);

		return mapping.findForward("ownerList");
	}

	// 跳转到业主添加页面
	public ActionForward toAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("toAdd");
	}

	// 完成业主添加操作
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		// 表单校验、
		if (oaf.getName() == null || "".equals(oaf.getName())) {
			request.setAttribute("ownerNameError", "请输入业主姓名");

			return mapping.findForward("toAdd");
		}
		if (oaf.getWorkUnit() == null || "".equals(oaf.getWorkUnit())) {
			request.setAttribute("ownerWorkUnitError", "请输入工作单位");

			return mapping.findForward("toAdd");
		}
		if (oaf.getPhone() == null || "".equals(oaf.getPhone())) {
			request.setAttribute("ownerPhoneError", "请输入联系电话");

			return mapping.findForward("toAdd");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(oaf.getPhone());
			if (!m.matches()) {
				request.setAttribute("ownerPhoneError", "请输入有效的联系电话！");
				return mapping.findForward("toAdd");
			}
		}
		if (oaf.getIdCard() == null || "".equals(oaf.getIdCard())) {
			request.setAttribute("ownerIdCardError", "请输入身份证号");

			return mapping.findForward("toAdd");
		} else {
			// 对输入的身份证号码进行校验
			Pattern p = Pattern
					.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
			Matcher m = p.matcher(oaf.getIdCard());
			if (!m.matches()) {
				request.setAttribute("ownerIdCardError", "身份证号码输入有误！");
				return mapping.findForward("toAdd");
			} else {
				if (managementService.findOwnerByIdCard(oaf.getIdCard()) != null) {
					request.setAttribute("ownerIdCardError",
							"该身份证号已注册，请核对后重新输入！");
					return mapping.findForward("toAdd");
				}
			}
		}
		if (oaf.getFmName() == null || "".equals(oaf.getFmName())) {
			request.setAttribute("ownerFamilyMemberError", "请输入家庭成员姓名！");

			return mapping.findForward("toAdd");
		}

		Owner owner = new Owner();
		PropertyUtils.copyProperties(owner, oaf);

		managementService.saveOwner(owner);

		return mapping.findForward("save");
	}

	// 跳转到业主修改页面
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 将默认值保存到ActionForm中，以便在JSP表单中显示该值。

		OwnerActionForm oaf = (OwnerActionForm) form;
		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);

		return mapping.findForward("ownerUpdate");
	}

	// 保存业主修改数据
	public ActionForward updateSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		// 表单校验、
		if (oaf.getName() == null || "".equals(oaf.getName())) {
			request.setAttribute("ownerNameError", "请输入业主姓名");

			return mapping.findForward("toUpdate");
		}
		if (oaf.getWorkUnit() == null || "".equals(oaf.getWorkUnit())) {
			request.setAttribute("ownerWorkUnitError", "请输入工作单位");

			return mapping.findForward("toUpdate");
		}
		if (oaf.getPhone() == null || "".equals(oaf.getPhone())) {
			request.setAttribute("ownerPhoneError", "请输入联系电话");

			return mapping.findForward("toUpdate");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(oaf.getPhone());
			if (!m.matches()) {
				request.setAttribute("ownerPhoneError", "请输入有效的联系电话！");
				return mapping.findForward("toUpdate");
			}
		}
		if (!oaf.getIdCard().equals(
				(managementService.findOwnerById(oaf.getId()).getIdCard()))) {// 校验身份证是否修改过，如若修改过再向下继续校验

			if (oaf.getIdCard() == null || "".equals(oaf.getIdCard())) {
				request.setAttribute("ownerIdCardError", "请输入身份证号");

				return mapping.findForward("toUpdate");
			} else {
				// 对输入的身份证号码进行校验
				Pattern p = Pattern
						.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
				Matcher m = p.matcher(oaf.getIdCard());
				if (!m.matches()) {
					request.setAttribute("ownerIdCardError", "身份证号码输入有误！");
					return mapping.findForward("toUpdate");
				} else {
					if (managementService.findOwnerByIdCard(oaf.getIdCard()) != null) {
						request.setAttribute("ownerIdCardError",
								"该身份证号已注册，请核对后重新输入！");
						return mapping.findForward("toUpdate");
					}
				}
			}
		}
		if (oaf.getFmName() == null || "".equals(oaf.getFmName())) {
			request.setAttribute("ownerFamilyMemberError", "请输入家庭成员姓名！");

			return mapping.findForward("toUpdate");
		}

		Owner owner = managementService.findOwnerById(oaf.getId());
		PropertyUtils.copyProperties(owner, oaf);
		managementService.updateOwner(owner);

		return mapping.findForward("updateSave");
	}

	// 完成业主删除操作
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		managementService.deleteOwnerById(oaf.getId());
		return mapping.findForward("delete");
	}

}
